// js/data/DataataManager.js
class DataManager {
  constructor() {
    this.userInfo = null;
    this.stockData = []; // 模拟K线数据
    this.leaderboard = [];
    this.currentGameScore = 0;
    this.init();
  }

  init() {
    // 初始化模拟K线数据
    this.generateMockStockData();
    // 从本地存储加载排行榜
    this.loadLeaderboard();
  }

  generateMockStockData(count = 50) {
    this.stockData = [];
    let lastClose = 100;
    for (let i = 0; i < count; i++) {
      const open = lastClose + (Math.random() - 0.5) * 2;
      const close = open + (Math.random() - 0.5) * 4;
      const high = Math.max(open, close) + Math.random() * 2;
      const low = Math.min(open, close) - Math.random() * 2;
      this.stockData.push({
        time: i,
        open: parseFloat(open.toFixed(2)),
        close: parseFloat(close.toFixed(2)),
        high: parseFloat(high.toFixed(2)),
        low: parseFloat(low.toFixed(2)),
      });
      lastClose = close;
    }
  }

  setUserInfo(info) {
    this.userInfo = info;
  }

  getUserInfo() {
    return this.userInfo;
  }

  getStockData() {
    return this.stockData;
  }

  setCurrentScore(score) {
    this.currentGameScore = score;
  }

  getCurrentScore() {
    return this.currentGameScore;
  }

  updateLeaderboard(score) {
    if (!this.userInfo) return;
    this.leaderboard.push({
      nickname: this.userInfo.nickName,
      avatarUrl: this.userInfo.avatarUrl,
      score: score,
    });
    this.leaderboard.sort((a, b) => b.score - a.score);
    this.leaderboard = this.leaderboard.slice(0, 10); // 只保留前10名
    this.saveLeaderboard();
  }

  getLeaderboard() {
    return this.leaderboard;
  }

  saveLeaderboard() {
    wx.setStorageSync('leaderboard', this.leaderboard);
  }

  loadLeaderboard() {
    try {
      const stored = wx.getStorageSync('leaderboard');
      if (stored) {
        this.leaderboard = stored;
      }
    } catch (e) {
      console.error("Failed to load leaderboard from storage.", e);
    }
  }
}

// 导出单例实例
export default new DataManager();
